package cn.turboinfo.fuyang.api.domain.admin.usecase.spec;

import cn.turboinfo.fuyang.api.domain.common.service.spec.SpecService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.pojo.spec.Spec;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.Stack;

@Slf4j
@RequiredArgsConstructor
@Component
public class SpecAncestorsUpdateUseCase extends AbstractUseCase<SpecAncestorsUpdateUseCase.InputData, SpecAncestorsUpdateUseCase.OutputData> {
    private final SpecService specService;

    @Override
    protected OutputData doAction(InputData inputData) {
        Stack<Spec> stack = new Stack<>();

        Long id = inputData.getId();

        if (id != null && id != 0) {
            Long ancestor = id;
            while (true) {
                Spec spec = specService.getByIdEnsure(ancestor);
                stack.push(spec);
                if (spec.getParentId() == 0 || spec.getParentId().equals(spec.getId())) {
                    break;
                }
                ancestor = spec.getParentId();
            }
            Collections.reverse(stack);
        }
        return OutputData.builder()
                .list(stack)
                .build();
    }

    @EqualsAndHashCode(
            callSuper = true
    )
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class InputData extends AbstractUseCase.InputData {

        private Long id;

    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {

        private Collection<Spec> list;
    }
}
